package com.symaster.common.swing;

import com.symaster.common.config.Config;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author yinmiao
 * @version 2022-12-01 14:21
 */
public class TextLoader {

    private final Set<TextChangeListener> textChangeListeners;
    private final Config config;

    public TextLoader(String file, Map<String, String> defaultText) {
        this.textChangeListeners = new HashSet<>();
        if (StringUtils.isNotEmpty(file)) {
            this.config = new Config(file, defaultText);
        } else {
            this.config = null;
        }
    }

    public TextLoader(String file) {
        this.textChangeListeners = new HashSet<>();
        if (StringUtils.isNotEmpty(file)) {
            this.config = new Config(file);
        } else {
            this.config = null;
        }
    }

    public void addTextChangeListener(TextChangeListener listener) {
        textChangeListeners.add(listener);
    }

    public String getText(String key) {
        return config.get(key);
    }

    public void updateText() {
        if (textChangeListeners.size() == 0) {
            return;
        }
        textChangeListeners.forEach(TextChangeListener::allChange);
    }

    public interface TextChangeListener {
        void allChange();
    }
}
